<?php

namespace App\Console\Commands\Test;

use App\Jobs\Test\Order\AutoCloseQueue as OrderAutoCloseQueue;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class OrderExpireListen extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:auto-close';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'order auto close';

    private $logger;


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->logger = Log::channel('console');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $cachedb = config('database.redis.cache.database', 1);

        $pattern = '__keyevent@' . $cachedb . '__:expired';

        try {

            Redis::connection('cache')->subscribe([$pattern], function ($channel) {

                list($laravelprx, $keyType, $orderId) = explode(':', $channel);

                switch ($keyType) {
                    case 'ORDER_AUTO_CLOSE':

                        OrderAutoCloseQueue::dispatch($orderId)->onConnection('redis')->onQueue('order-close');


                        $this->info($orderId);

                        break;
                    default:
                        echo 'default' . PHP_EOL;
                        break;
                }
            });

        } catch (\Exception $exception) {
            logger($exception->getMessage());
        }
    }
}
